
package org.jivesoftware.util;

/**
 * 链表实现
 * @author zhujin
 *
 * @param <E>
 */
public class LinkedList<E> {

    private LinkedListNode<E> head;

    public LinkedList() {
    	head = new LinkedListNode<E>();
    }

    public LinkedListNode<E> getFirst() {
        LinkedListNode<E> node = head.next;
        if (node == head) {
            return null;
        }
        return node;
    }

    public LinkedListNode<E> getLast() {
        LinkedListNode<E> node = head.previous;
        if (node == head) {
            return null;
        }
        return node;
    }

    public LinkedListNode<E> addFirst(LinkedListNode<E> node) {
    	return node.insert(head.next, head);
    }

    public LinkedListNode<E> addFirst(E object) {
        return new LinkedListNode<E>(object, head.next, head);
    }

    public LinkedListNode<E> addLast(LinkedListNode<E> node) {
    	return node.insert(head, head.previous);
    }

    public LinkedListNode<E> addLast(E object) {
        return new LinkedListNode<E>(object, head, head.previous);
    }

    public void clear() {
        //Remove all references in the list.
        LinkedListNode<E> node = getLast();
        while (node != null) {
            node.remove();
            node = getLast();
        }

        //Re-initialize.
        head.next = head.previous = head;
    }

    @Override
	public String toString() {
        LinkedListNode<E> node = head.next;
        StringBuilder buf = new StringBuilder();
        while (node != head) {
            buf.append(node.toString()).append(", ");
            node = node.next;
        }
        return buf.toString();
    }
}
